//
//  VideoTableViewCell.m
//  ToYourHeartNews
//
//  Created by XJing on 16/1/18.
//  Copyright © 2016年 www.lanou3g.com 蓝鸥. All rights reserved.
//

#import "VideoTableViewCell.h"
#import "Player.h"
#import "VideoBigViewController.h"
@interface VideoTableViewCell ()
@property (nonatomic, strong)AVPlayerItem *playerItem;
@property (nonatomic, strong)AVPlayer *player;
@property (nonatomic, strong)AVPlayerLayer *playerLayer;
@property (nonatomic, strong)UIView *playerView;
@property (nonatomic, strong)UIView *middleView;//中间区域 放播放按钮
@property (nonatomic, strong)UIButton *playBtn;//播放按钮
@property (nonatomic, strong)UIView *buttomView;//底部控制区域
@property (nonatomic, strong)UIButton *biggerBtn;//放大按钮
@property (nonatomic, strong)UISlider *slider;//进度条
@property (nonatomic, strong)UILabel *timLable;//时间显示
@property (nonatomic, assign)BOOL isDismiss;
@property (nonatomic, assign)BOOL isPlay;
@property (nonatomic, assign)CGFloat totalDurtion;//总时长
@end
@implementation VideoTableViewCell
- (void)dealloc
{
    [_titleLable release];
    [_detailLable release];
    [_timeImg release];
    [_timeLable release];
    [_playImage release];
    [_playLable release];
    [_commentLable release];
    [_share release];
    [super dealloc];
}
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.titleLable = [[UILabel alloc]init];
//        _titleLable.backgroundColor = [UIColor redColor];
        [self.contentView addSubview:_titleLable];
        [_titleLable release];
        
        self.detailLable = [[UILabel alloc]init];
//        _detailLable.backgroundColor = [UIColor orangeColor];
        [self.contentView addSubview:_detailLable];
        [_detailLable release];
        
        self.timeImg = [[UIImageView alloc]init];
//        _timeImg.backgroundColor = [UIColor yellowColor];
        [self.contentView addSubview:_timeImg];
        [_timeImg release];
        
        self.timeLable = [[UILabel alloc]init];
//        _timeLable.backgroundColor = [UIColor greenColor];
        [self.contentView addSubview:_timeLable];
        [_timeLable release];
        
        self.playImage = [[UIImageView alloc]init];
//        _playImage.backgroundColor = [UIColor blueColor];
        [self.contentView addSubview:_playImage];
        [_playImage release];
        
        self.playLable = [[UILabel alloc]init];
//        _playLable.backgroundColor = [UIColor magentaColor];
        [self.contentView addSubview:_playLable];
        [_playLable release];
        
        self.commentLable = [[UILabel alloc]init];
//        _commentLable.backgroundColor = [UIColor cyanColor];
        [self.contentView addSubview:_commentLable];
        [_commentLable release];
        
        self.share = [UIButton buttonWithType:UIButtonTypeSystem];
//        _share.backgroundColor = [UIColor grayColor];
        [self.contentView addSubview:_share];
        
        //创建播放playerView
        self.playerView = [[UIView alloc]init];
        _playerView.backgroundColor = [UIColor purpleColor];
        [self.contentView addSubview:_playerView];
        [_playerView release];

        self.middleView = [[UIView alloc]init];
//        _middleView.backgroundColor = [UIColor blueColor];
        [_playerView addSubview:_middleView];
        [_middleView release];
        
        self.playBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_playBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-shipin"] forState:UIControlStateNormal];
       [_middleView addSubview:_playBtn];
        
        
        self.buttomView = [[UIView alloc]init];
        _buttomView.backgroundColor = [UIColor lightGrayColor];
        [_playerView addSubview:_buttomView];
        [_buttomView release];
        
        self.biggerBtn = [UIButton buttonWithType:UIButtonTypeSystem];
        [_biggerBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-fangda"] forState:UIControlStateNormal];
        [_biggerBtn addTarget:self action:@selector(biggerAction) forControlEvents:UIControlEventTouchUpInside];
        [_buttomView addSubview:_biggerBtn];
        
        self.slider = [[UISlider alloc]init];
        // 初始化进度条
        _slider.value = 0;
        [_buttomView addSubview:_slider];

        
        self.timLable = [[UILabel alloc]init];
        //_timLable.backgroundColor = [UIColor redColor];
        // 初始化时间显示
        _timLable.text = @"00:00/00:00";
        [_buttomView addSubview:_timLable];
        
    }
    return self;
}
-(void)layoutSubviews
{
    [super layoutSubviews];
    //title
    _titleLable.frame = CGRectMake(10, 10, self.contentView.frame.size.width - 20, self.contentView.frame.size.height / 10);
    //detail
    _detailLable.frame = CGRectMake(10, _titleLable.frame.origin.y + _titleLable.frame.size.height, _titleLable.frame.size.width, _titleLable.frame.size.height / 2);
    _detailLable.font = [UIFont systemFontOfSize:14];
    _detailLable.textColor = [UIColor grayColor];
    //view
    _playerView.frame = CGRectMake(10, _detailLable.frame.origin.y + _detailLable.frame.size.height + 10, _detailLable.frame.size.width, self.contentView.frame.size.height / 3 * 2);
    //创建AVplayer
    [self creatAVplayer];
    self.isPlay = NO;
    [_player pause];
    //AVplayer大小
    _playerLayer.frame = CGRectMake(0, 0, _detailLable.frame.size.width, self.contentView.frame.size.height / 3 * 2);
    [_player play];
    //timeImage
    self.timeImg.frame = CGRectMake(_detailLable.frame.origin.x, _playerView.frame.origin.y + _playerView.frame.size.height + 10, 20, 20);
    _timeImg.image = [UIImage imageNamed:@"iconfont-clock"];
    //timeLable
    self.timeLable.frame = CGRectMake(_timeImg.frame.origin.x + _timeImg.frame.size.width + 2, _timeImg.frame.origin.y, _timeImg.frame.size.width * 2, _timeImg.frame.size.height);
    _timeLable.font = [UIFont systemFontOfSize:10];
    //playImage
    self.playImage.frame = CGRectMake(_timeLable.frame.origin.x + _timeLable.frame.size.width + 10, _timeImg.frame.origin.y, _timeImg.frame.size.width, _timeImg.frame.size.height);
    _playImage.image = [UIImage imageNamed:@"iconfont-shipin"];
    //playLable
    self.playLable.frame = CGRectMake(_playImage.frame.origin.x + _playImage.frame.size.width + 2, _playImage.frame.origin.y, _timeLable.frame.size.width, _playImage.frame.size.height);
    _playLable.font = [UIFont systemFontOfSize:10];
    //comment
    self.commentLable.frame = CGRectMake(self.contentView.frame.size.width / 4 * 3, _timeImg.frame.origin.y, _timeLable.frame.size.width, _timeLable.frame.size.height);
    _commentLable.font = [UIFont systemFontOfSize:10];
    //share
    self.share.frame = CGRectMake(_commentLable.frame.origin.x + _commentLable.frame.size.width + 2, _timeImg.frame.origin.y, _timeLable.frame.size.height, _timeLable.frame.size.height);
    [_share setBackgroundImage:[UIImage imageNamed:@"iconfont-share"] forState:UIControlStateNormal];
    [_share addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
//    [_player pause];
//    _isPlay = NO;
    
    // 添加手势 隐藏边栏
    [self addTapToDismissBar];
    // 通过通知中心监听 播放器/视频/页面 状态信息
    [self addNotificationCenter];
    // 进度条监听
    [self progressObserving];
    
}
//创建AVplayer
-(void)creatAVplayer
{
    //创建视频对象
    self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:_str]];
    self.player = [AVPlayer playerWithPlayerItem:_playerItem];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    _playerLayer.frame = _playerView.frame;
    _playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [_playerView.layer insertSublayer:_playerLayer atIndex:0];
   
    //创建中间视图
    self.middleView.frame = CGRectMake(_playerView.frame.size.width / 5 * 2, _playerView.frame.size.height / 3 * 1, _playerView.frame.size.width / 7, _playerView.frame.size.width / 7);
    //播放按钮
    _playBtn.frame = CGRectMake(0, 0, _middleView.frame.size.width, _middleView.frame.size.height);
    [_playBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-shipin"] forState:UIControlStateNormal];
    [_playBtn addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
//    [_middleView addSubview:_playBtn];
    //创建底部视图
    self.buttomView.frame = CGRectMake(0, _playerView.frame.size.height - _playerView.frame.size.height / 10, _playerView.frame.size.width, _playerView.frame.size.height / 10);
    //滑动进度条
    _slider.frame = CGRectMake(0, 0, _buttomView.frame.size.width / 5 * 3, _buttomView.frame.size.height);
    [_slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    
    //时间显示
    _timLable.frame = CGRectMake(_slider.frame.size.width + 10, _slider.frame.origin.y, _buttomView.frame.size.width / 4 , _slider.frame.size.height);
    _timLable.textColor = [UIColor whiteColor];
    _timLable.font = [UIFont systemFontOfSize:10];
    
    //放大按钮
    _biggerBtn.frame = CGRectMake(_timLable.frame.origin.x + _timLable.frame.size.width + 15, _timLable.frame.origin.y, _timLable.frame.size.width / 4, _timLable.frame.size.width / 4);
}
-(void)biggerAction
{
    VideoBigViewController *bigVC = [[VideoBigViewController alloc]init];
    bigVC.str = _str;
    [self.delegate passVideo];
}
//进度条件听 获取视频时长
- (void)progressObserving
{
    // 设置(1,1) 每秒刷新一次
    // 参数1 : 时间监听器 刷新时间
    // 参数2 : 队列
    // 参数3 : 刷新时执行的block
    __block  UITableViewCell *vc = self;
    [_player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        // 获取总时长
        CGFloat duration = CMTimeGetSeconds(_playerItem.duration);
        // 获取当前时长
        CGFloat currentDuration = CMTimeGetSeconds(_player.currentTime);
        // 获取倒计时
        CGFloat rem = duration - currentDuration;
        
        // 剩余时间
        NSString *totalT = [NSString stringWithFormat:@"%02d:%2d", (int)rem / 60, (int)rem % 60];
        // 当前时间
        NSString *currentT = [NSString stringWithFormat:@"%02d:%2d", (int)currentDuration / 60, (int)currentDuration % 60];
        // 拼接时间
        NSString *timeStr = [NSString stringWithFormat:@"%@/%@", currentT, totalT];
       self.timLable.text = timeStr;
        // 保存总时长 用于slider手动控制进度
        self.totalDurtion = duration;
        // 控制slider的当前进度
        _slider.value = currentDuration / duration;
    }];
}

#pragma mark - 通知中心
- (void)addNotificationCenter
{
    // 是否播放完成
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    // 监听屏幕旋转
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarPositionChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}
//视频播放结束后出发的方法
- (void)moviePlayDidEnd:(NSNotificationCenter *)noti
{
    NSLog(@"视频播放已经结束");
}
#pragma mark - 添加手势
- (void)addTapToDismissBar
{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_playerView addGestureRecognizer:tap];
}
#pragma mark - 隐藏边栏
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    // 初始播放 还未隐藏 isDismiss = NO
    // 隐藏
    if (!_isDismiss) {
        // 隐藏边栏
        [UIView animateWithDuration:0.5 animations:^{
            _buttomView.alpha = 0;
            _middleView.alpha = 0;
        }];
    } else {
        // 显示边栏
        [UIView animateWithDuration:0.5 animations:^{
            _buttomView.alpha = 0.8;
            _middleView.alpha = 0.8;
        }];
    }
    _isDismiss = !_isDismiss;
}
//播放按钮方法
-(void)playAction:(UIButton *)sender
{
    // BOOL判断
    if (_isPlay) {
        // 正在播放时 暂停
        [_player pause];
        [sender setBackgroundImage:[UIImage imageNamed:@"iconfont-shipin"] forState:UIControlStateNormal];
    } else {
        [_player play];
        // 隐藏边栏
        [UIView animateWithDuration:0.5 animations:^{
            _buttomView.alpha = 0;
            _middleView.alpha = 0;
        }];
        [sender setBackgroundImage:[UIImage imageNamed:@"iconfont-bofang"] forState:UIControlStateNormal];
    }
    _isPlay = !_isPlay;
}
-(void)sliderAction:(UISlider *)sender
{
    // 先暂停
    [_player pause];
    // 当前时间
    CGFloat current = sender.value * _totalDurtion;
    // 创建CMTime
    CMTime time = CMTimeMake(current, 1);
    // 把time给播放器 跳转到对一个的时间点
    [_player seekToTime:time completionHandler:^(BOOL finished) {
        [_player play];
    }];

}
- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
